#include "operations_user_service.h"
#include "ui_operations_user_service.h"
#include <QTableWidgetItem>
#include <QPushButton>
#include <QHBoxLayout>
#include <QWidget>
#include <QColor>
#include <QMessageBox>
#include <QHeaderView>
#include <QDateTime>
#include <QDebug>

operations_user_service::operations_user_service(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::operations_user_service)
    , currentPage(1)
    , totalPages(1)
    , pageSize(10)
    , totalRecords(0)
    , m_api(Api::getInstance())
{
    ui->setupUi(this);
    
    // 初始化UI控件
    updateButtonStates();
    updateSearchControls();
    
    // 加载初始数据
    loadUserData();
    
    // 设置窗口标题
    setWindowTitle(tr("用户服务管理系统"));

}

operations_user_service::~operations_user_service()
{
    this->close();
    delete ui;
    // 不需要手动关闭数据库连接，由Api单例管理
}

void operations_user_service::loadUserData()
{
    clearTable();
    
    // 使用API获取用户数据
    QJsonObject result;
    if (currentSearchText.isEmpty()) {
        result = m_api->getUsers(currentPage, pageSize);
    } else {
        // 使用异步版本的searchUsers
        m_api->searchUsers(currentSearchText, currentPage, pageSize, [this](bool success, const QJsonObject& response, const QString& errorMsg, int statusCode) {
            if (success && response["success"].toBool()) {
                QJsonArray users = response["users"].toArray();
                totalRecords = response["total"].toString().toInt();
                totalPages = (totalRecords + pageSize - 1) / pageSize;
                
                QList<QMap<QString, QVariant>> userData;
                for (const QJsonValue &userValue : users) {
                    QJsonObject user = userValue.toObject();
                    QMap<QString, QVariant> userMap;
                    userMap["id"] = user["id"].toString();
                    userMap["name"] = user["name"].toString();
                    userMap["email"] = user["email"].toString();
                    userMap["phone"] = user["phone"].toString();
                    userMap["status"] = user["status"].toString();
                    userData.append(userMap);
                }
                
                populateUserTable(userData);
                updatePageInfo();
                updateStatistics();
                updateTableButtons();
            } else {
                QString errorMsg = response["error"].toString();
                showMessage(tr("查询用户数据失败: %1").arg(errorMsg), tr("错误"));
            }
        });
        return; // 异步调用，直接返回
    }
    
    if (result["success"].toBool()) {
        QJsonArray users = result["users"].toArray();
        totalRecords = result["total"].toString().toInt();
        totalPages = (totalRecords + pageSize - 1) / pageSize;
        
        QList<QMap<QString, QVariant>> userData;
        for (const QJsonValue &userValue : users) {
            QJsonObject user = userValue.toObject();
            QMap<QString, QVariant> userMap;
            userMap["id"] = user["id"].toString();
            userMap["name"] = user["name"].toString();
            userMap["email"] = user["email"].toString();
            userMap["phone"] = user["phone"].toString();
            userMap["status"] = user["status"].toString();
            userData.append(userMap);
        }
        
        populateUserTable(userData);
        updatePageInfo();
        updateStatistics();
        updateTableButtons();
    } else {
        QString errorMsg = result["error"].toString();
        showMessage(tr("查询用户数据失败: %1").arg(errorMsg), tr("错误"));
    }
}

void operations_user_service::clearTable()
{
    ui->userTable->setRowCount(0);
}

void operations_user_service::populateUserTable(const QList<QMap<QString, QVariant>> &userData)
{
    ui->userTable->setRowCount(userData.size());
    
    for (int i = 0; i < userData.size(); ++i) {
        addTableRow(i, userData[i]);
    }
}

void operations_user_service::addTableRow(int row, const QMap<QString, QVariant> &userData)
{
    // 用户名(作为ID)
    QTableWidgetItem *idItem = new QTableWidgetItem(userData["id"].toString());
    idItem->setTextAlignment(Qt::AlignCenter);
    ui->userTable->setItem(row, 0, idItem);
    
    // 姓名
    QTableWidgetItem *nameItem = new QTableWidgetItem(userData["name"].toString());
    nameItem->setTextAlignment(Qt::AlignCenter);
    ui->userTable->setItem(row, 1, nameItem);
    
    // 邮箱
    QTableWidgetItem *emailItem = new QTableWidgetItem(userData["email"].toString());
    emailItem->setTextAlignment(Qt::AlignCenter);
    ui->userTable->setItem(row, 2, emailItem);
    
    // 电话
    QTableWidgetItem *phoneItem = new QTableWidgetItem(userData["phone"].toString());
    phoneItem->setTextAlignment(Qt::AlignCenter);
    ui->userTable->setItem(row, 3, phoneItem);
    
    // 状态
    QString status = userData["status"].toString();
    QTableWidgetItem *statusItem = new QTableWidgetItem(status);
    statusItem->setTextAlignment(Qt::AlignCenter);
    
    // 根据状态设置不同的颜色
    if (status == tr("正常")) {
        statusItem->setForeground(QColor(0, 128, 0));  // 绿色
    } else if (status == tr("冻结")) {
        statusItem->setForeground(QColor(255, 0, 0));  // 红色
    }
    
    ui->userTable->setItem(row, 4, statusItem);
    
    // 操作按钮
    QWidget *buttonWidget = new QWidget();
    QHBoxLayout *buttonLayout = new QHBoxLayout(buttonWidget);
    buttonLayout->setContentsMargins(5, 2, 5, 2);
    buttonLayout->setSpacing(5);
    
    // 查看按钮
    QPushButton *viewButton = new QPushButton(tr("查看"));
    viewButton->setFixedSize(50, 25);
    viewButton->setStyleSheet("QPushButton { background-color: #4CAF50; color: white; border: none; border-radius: 3px; } QPushButton:hover { background-color: #45a049; }");
    connect(viewButton, &QPushButton::clicked, [this, userData]() {
            viewUserDetails(userData["id"].toString().toInt());
        });
    
    // 状态切换按钮
    QPushButton *statusButton;
    if (status == tr("正常")) {
        statusButton = new QPushButton(tr("冻结"));
        statusButton->setStyleSheet("QPushButton { background-color: #f44336; color: white; border: none; border-radius: 3px; } QPushButton:hover { background-color: #da190b; }");
        connect(statusButton, &QPushButton::clicked, [this, userData]() {
            freezeUser(userData["id"].toString().toInt());
        });
    } else {
        statusButton = new QPushButton(tr("解封"));
        statusButton->setStyleSheet("QPushButton { background-color: #FF9800; color: white; border: none; border-radius: 3px; } QPushButton:hover { background-color: #e68900; }");
        connect(statusButton, &QPushButton::clicked, [this, userData]() {
            unfreezeUser(userData["id"].toString().toInt());
        });
    }
    statusButton->setFixedSize(50, 25);
    
    buttonLayout->addWidget(viewButton);
    buttonLayout->addWidget(statusButton);
    buttonLayout->addStretch();
    
    ui->userTable->setCellWidget(row, 5, buttonWidget);
}

void operations_user_service::updatePageInfo()
{
    // 使用API获取用户总数，不再使用本地SQLite
    QJsonObject params;
    params["page"] = 1;
    params["pageSize"] = 1;  // 只需要获取总数
    
    m_api->getUsers(params, [this](bool success, const QJsonObject& response, const QString& errorMsg, int statusCode) {
        if (success && response.value("success").toBool()) {
            totalRecords = response["total"].toString().toInt();
        } else {
            totalRecords = 0;
            qDebug() << "获取用户总数失败:" << errorMsg;
        }
        
        // 计算总页数
        totalPages = (totalRecords + pageSize - 1) / pageSize;
        
        // 更新页码显示
        ui->pageLabel->setText(tr("第 %1 页，共 %2 页").arg(currentPage).arg(totalPages));
    });
}

void operations_user_service::updateStatistics()
{
    // 使用API获取用户统计数据
    QJsonObject result = m_api->getUserStatistics();
    
    if (result["success"].toBool()) {
        QJsonObject stats = result["statistics"].toObject();
        
        // 总用户数
        ui->totalUsersLabel->setText(tr("总用户数：%1").arg(stats["totalUsers"].toString()));
        
        // 正常用户数
        ui->normalUsersLabel->setText(tr("正常用户：%1").arg(stats["normalUsers"].toString()));
        
        // 冻结用户数
        ui->frozenUsersLabel->setText(tr("冻结用户：%1").arg(stats["frozenUsers"].toString()));
    } else {
        QString errorMsg = result["error"].toString();
        qDebug() << "获取用户统计失败:" << errorMsg;
    }
}

void operations_user_service::updateTableButtons()
{
    // 更新分页按钮状态
    ui->firstPageBtn->setEnabled(currentPage > 1);
    ui->prevPageBtn->setEnabled(currentPage > 1);
    ui->nextPageBtn->setEnabled(currentPage < totalPages);
    ui->lastPageBtn->setEnabled(currentPage < totalPages);
}

void operations_user_service::updateButtonStates()
{
    // 初始化按钮状态
    updateTableButtons();
}

void operations_user_service::updateSearchControls()
{
    // 设置搜索控件的初始状态
    ui->statusComboBox->setCurrentIndex(0);  // 全部状态
    ui->searchEdit->clear();                  // 清空搜索框
}

QString operations_user_service::buildWhereClause()
{
    QStringList conditions;
    
    // 搜索条件
    QString searchText = ui->searchEdit->text().trimmed();
    if (!searchText.isEmpty()) {
        conditions.append(QString("(username LIKE '%%1%' OR email LIKE '%%1%' OR phone LIKE '%%1%')").arg(searchText));
    }
    
    // 状态筛选
    QString statusFilter = ui->statusComboBox->currentText();
    if (statusFilter != tr("全部状态")) {
        if (statusFilter == tr("正常")) {
            conditions.append("status = 'active'");
        } else if (statusFilter == tr("冻结")) {
            conditions.append("status = 'inactive'");
        }
    }
    
    // 移除年龄筛选，因为orders表没有age字段
    
    return conditions.isEmpty() ? "" : "WHERE " + conditions.join(" AND ");
}

void operations_user_service::showMessage(const QString &message, const QString &title)
{
    QMessageBox::information(this, title, message);
}

bool operations_user_service::confirmAction(const QString &message, const QString &title)
{
    return QMessageBox::question(this, title, message, QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes;
}

// 槽函数实现
void operations_user_service::on_searchButton_clicked()
{
    currentPage = 1;
    loadUserData();
}

void operations_user_service::on_refreshButton_clicked()
{
    saveAndRefreshData();
}

void operations_user_service::on_firstPageBtn_clicked()
{
    currentPage = 1;
    loadUserData();
}

void operations_user_service::on_prevPageBtn_clicked()
{
    if (currentPage > 1) {
        currentPage--;
        loadUserData();
    }
}

void operations_user_service::on_nextPageBtn_clicked()
{
    if (currentPage < totalPages) {
        currentPage++;
        loadUserData();
    }
}

void operations_user_service::on_lastPageBtn_clicked()
{
    currentPage = totalPages;
    loadUserData();
}

void operations_user_service::on_statusComboBox_currentTextChanged(const QString &text)
{
    currentPage = 1;
    loadUserData();
}

void operations_user_service::on_searchEdit_returnPressed()
{
    on_searchButton_clicked();
}

void operations_user_service::on_userTable_cellClicked(int row, int column)
{
    // 单元格点击事件处理
    Q_UNUSED(row)
    Q_UNUSED(column)
}

void operations_user_service::on_userTable_cellDoubleClicked(int row, int column)
{
    Q_UNUSED(column)
    // 双击查看用户详情
    QTableWidgetItem *idItem = ui->userTable->item(row, 0);
    if (idItem) {
        int userId = idItem->text().remove(QRegularExpression("[^0-9]")).toInt();
        viewUserDetails(userId);
    }
}

void operations_user_service::viewUserDetails(int userId)
{
    // 使用API获取用户详情
    QJsonObject result = m_api->getUserDetails(userId);
    
    if (result["success"].toBool()) {
        QJsonObject user = result["user"].toObject();
        QString details = QString("用户名：%1\n用户Id：%2\n邮箱：%3\n电话：%4\n状态：%5")
                          .arg(user["name"].toString())
                          .arg(user["user_id"].toString())
                          .arg(user["email"].toString())
                          .arg(user["phone"].toString())
                          .arg(user["status"].toString());
        
        showMessage(details, "用户详情");
    } else {
        QString errorMsg = result["error"].toString();
        showMessage(tr("获取用户详情失败：%1").arg(errorMsg), "错误");
    }
}

void operations_user_service::freezeUser(int userId)
{
    if (!confirmAction("确定要冻结该用户吗？", "确认冻结")) {
        return;
    }
    
    // 使用API冻结用户
    QJsonObject result = m_api->freezeUser(userId);
    
    if (result["success"].toBool()) {
        showMessage("用户已冻结！", "成功");
        loadUserData();
    } else {
        QString errorMsg = result["error"].toString();
        showMessage(tr("冻结用户失败：%1").arg(errorMsg), "错误");
    }
}

void operations_user_service::unfreezeUser(int userId)
{
    if (!confirmAction("确定要解封该用户吗？", "确认解封")) {
        return;
    }
    
    // 使用API解封用户
    QJsonObject result = m_api->unfreezeUser(userId);
    
    if (result["success"].toBool()) {
        showMessage("用户已解封！", "成功");
        loadUserData();
    } else {
        QString errorMsg = result["error"].toString();
        showMessage(tr("解封用户失败：%1").arg(errorMsg), "错误");
    }
}

void operations_user_service::toggleUserStatus(int userId, const QString &currentStatus)
{
    // 使用API切换用户状态，不再使用本地SQLite
    QString newStatus;
    QString action;
    if (currentStatus == tr("正常")) {
        // 使用冻结用户API
        QJsonObject result = m_api->freezeUser(userId);
        if (result["success"].toBool()) {
            showMessage("用户冻结成功！", "成功");
            loadUserData();
        } else {
            QString errorMsg = result["error"].toString();
            showMessage(tr("用户冻结失败：%1").arg(errorMsg), "错误");
        }
    } else {
        // 使用解封用户API
        QJsonObject result = m_api->unfreezeUser(userId);
        if (result["success"].toBool()) {
            showMessage("用户解封成功！", "成功");
            loadUserData();
        } else {
            QString errorMsg = result["error"].toString();
            showMessage(tr("用户解封失败：%1").arg(errorMsg), "错误");
        }
    }
}

bool operations_user_service::saveUserData()
{
    // 这里可以添加数据保存逻辑
    // 目前主要是保存用户状态变更，其他字段在具体操作时已经保存
    return true;
}

void operations_user_service::saveAndRefreshData()
{
    if (saveUserData()) {
        refreshData();
        showMessage("数据已保存并刷新！", "成功");
    } else {
        showMessage("数据保存失败！", "错误");
    }
}

void operations_user_service::refreshData()
{
    loadUserData();
}

void operations_user_service::applyFilters()
{
    currentPage = 1;
    loadUserData();
}

QString operations_user_service::getStatusColor(const QString &status)
{
    if (status == "正常") {
        return "green";
    } else if (status == "冻结") {
        return "red";
    }
    return "black";
}

QString operations_user_service::getAgeRange(int age)
{
    if (age < 18) {
        return "18岁以下";
    } else if (age >= 18 && age <= 25) {
        return "18-25岁";
    } else if (age >= 26 && age <= 35) {
        return "26-35岁";
    } else if (age >= 36 && age <= 50) {
        return "36-50岁";
    } else {
        return "50岁以上";
    }
}
